<?php

namespace App\Models;

use Validator;


class Member extends BaseModel
{
    protected $table = "member";

    public $timestamps = false;


    /* 用户模型自动验证 */
    protected $_validate = [
        /* 验证用户名 */
        'username' => 'required|unique:ucenter_member|digits_between:1,30',
        /* 验证密码 */
        'password' => 'required|digits_between:6,30',
        /* 验证邮箱 */
        'email' => 'required|email|unique:ucenter_member|digits_between:1,30',
        /* 验证手机号码 */
        'mobile' => ['regex:^(1(([35][0-9])|(47)|[8][01236789]))\d{8}$', 'required', 'unique:ucenter_member'],
    ];

    protected $_message = [
        /* 用户名验证信息 */
        'username.required' => '用户名必填',
        'username.unique' => '用户名被占用',
        'username.digits_between' => '用户名长度不合法必须1-30位字符',
        /* 密码验证信息 */
        'password.required' => '密码必填',
        'password.digits_between' => '密码长度不合法必须6-30位字符',
        /* 邮箱验证信息 */
        'email.required' => '邮箱必填',
        'email.email' => '邮箱格式不正确',
        'email.digits_between' => '邮箱长度不合法必须1-32位字符',
        'email.unique' => '邮箱被占用',
        /* 手机号码验证信息 */
        'mobile.required' => '手机号必填',
        'mobile.unique' => '手机号被占用',
        'mobile.regex' => '手机号格式不正确',
    ];

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 注册一个新用户
     * @param  string $username 用户名
     * @param  string $password 用户密码
     * @param  string $email 用户邮箱
     * @param  string $mobile 用户手机号码
     * @return integer          注册成功-用户信息，注册失败-错误编号
     */
    public function register($username, $password, $email, $mobile)
    {
        $data = [
            'username' => $username,
            'password' => $password,
            'email' => $email,
            'mobile' => $mobile,
        ];

        //验证手机
        if (empty($data['mobile'])) unset($data['mobile']);

        $validator = Validator::make($data, $this->_validate);

        //验证失败
        if ($validator->fails()) {
            //返回所有错误信息
            return $validator->errors()->all();
        }
        $data['password'] = md5($data['password']);
        $data['reg_time'] = time();
        $data['reg_ip'] = request()->ip();
        $data['update_time'] = time();
        $data['reg_time'] = time();
        $data['status'] = 1;
        /* 添加用户 */
        $uid = $this->_add($data);
        return $uid ? $uid : 0; //0-未知错误，大于0-注册成功
    }

    /**
     * 用户登录认证
     * @param  string $username 用户名
     * @param  string $password 用户密码
     * @param  integer $type 用户名类型 （1-用户名，2-邮箱，3-手机，4-UID）
     * @return integer           登录成功-用户ID，登录失败-错误编号
     */
    public function login($request, $type = 1)
    {
        $username = $request['username'];
        $password = $request['password'];
        $where = array();
        switch ($type) {
            case 1:
                $where['username'] = $username;
                break;
            case 2:
                $where['email'] = $username;
                break;
            case 3:
                $where['mobile'] = $username;
                break;
            case 4:
                $where['id'] = $username;
                break;
            default:
                return 0; //参数错误
        }

        /* 获取用户数据 */
        $admin = $this->_getOne($where);
        if (!$admin || $admin['status'] != 1) {
            $this->error = '用户不存在或已被禁用！'; //应用级别禁用
            return false;
        }
        /* 验证用户密码 */
        if (md5($password) !== $admin['password']) {
            $this->error = '账号或密码错误';
            return false;
        }
        $this->updateLogin($admin); //更新用户登录信息
        $menu = new Menu();
        session(['menus' => $menu->getMenus()]);
        session()->save();
        //记录行为
        $actionLog = new ActionLog();
        $actionLog->action_log('admin_login', 'admin', $admin['id'], $admin['id']);
        return true;
    }


    /**
     * 获取用户信息
     * @param  string $uid 用户ID或用户名
     * @param  boolean $is_username 是否使用用户名查询
     * @return array                用户信息
     */
    public function info($uid, $is_username = false)
    {
        $where = [];
        if ($is_username) { //通过用户名获取
            $where['username'] = $uid;
        } else {
            $where['id'] = $uid;
        }

        $admin = $this->_getOne($where, 'id,username,email,mobile,status');
        if (is_array($admin) && $admin['status'] == 1) {
            return [$admin['id'], $admin['username'], $admin['email'], $admin['mobile']];
        } else {
            return -1; //用户不存在或被禁用
        }
    }

    /**
     * 检测用户信息
     * @param  string $field 用户名
     * @param  integer $type 用户名类型 1-用户名，2-用户邮箱，3-用户电话
     * @return integer         错误编号
     */
    public function checkField($field, $type = 1)
    {
        $data = [];
        switch ($type) {
            case 1:
                $data['username'] = $field;
                break;
            case 2:
                $data['email'] = $field;
                break;
            case 3:
                $data['mobile'] = $field;
                break;
            default:
                return 0; //参数错误
        }
        $validator = Validator::make($data, $this->_validate);
        //验证失败
        if ($validator->fails()) {
            //返回所有错误信息
            return $validator->errors()->all();
        }
        return true;
    }

    /**
     * 更新用户登录信息
     * @param  integer $uid 用户ID
     */
    protected function updateLogin($user)
    {
        /* 更新登录信息 */
        $data = [
            'last_login_time' => time(),
            'last_login_ip' => request()->ip()
        ];
        $this->_inc(['id' => $user['id']], 'login', 1, $data);

        /* 记录登录SESSION和COOKIES */
        $auth = [
            'uid' => $user['id'],
            'username' => $user['username'],
            'last_login_time' => $user['last_login_time'],
        ];
        session(['user_auth' => $auth]);
        session(['user_auth_sign' => data_auth_sign($auth)]);
    }

    /**
     * 更新用户信息
     * @param int $uid 用户id
     * @param string $password 密码，用来验证
     * @param array $data 修改的字段数组
     * @return true 修改成功，false 修改失败
     */
    public function updateUserFields($uid, $password, $data)
    {
        if (empty($uid) || empty($password) || empty($data)) {
            $this->error = '参数错误！';
            return false;
        }

        //更新前检查用户密码
        if (!$this->verifyUser($uid, $password)) {
            $this->error = '验证出错：密码不正确！';
            return false;
        }
        $validator = Validator::make($data, $this->_validate);
        //验证失败
        if ($validator->fails()) {
            //返回所有错误信息
            return false;
        }
        //更新用户信息
        return $this->_update(['id' => $uid], $data);
    }

    /**
     * 验证用户密码
     * @param int $uid 用户id
     * @param string $password_in 密码
     * @return true 验证成功，false 验证失败
     */
    public function verifyUser($uid, $password_in)
    {
        $password = $this->_getOne(['id' => $uid], 'password');
        if (md5($password_in) === $password) {
            return true;
        }
        return false;
    }

    public function getAdminList()
    {
        $nickname = request('nickname');
        $where['status'] = ['>=', 0];
        if (is_numeric($nickname)) {
            $where['uid'] = $nickname;
        } else {
            $where['nickname'] = ['like', '%' . $nickname . '%'];
        }
        $rows = $this->_getPageList($where);
        return int_to_string($rows);
    }

}